<template>
  <Page class="basic company">
    <template #header>
      <EdSelect v-model="params.villageId" :selectParams="projectNameParams" @emit-select-value="projectChange" ></EdSelect>
      <EdSelect v-model="params.locationType" :selectParams="locationTypeParams" ></EdSelect>
      <el-input placeholder="点位名称" v-model="params.locationName"></el-input>
      <el-button class="ed-button ed_black-bottom" @click="search()"><svg-icon class="svg-middle" icon-class="search-svg" />查询</el-button>
      <el-button class="ed-button ed_white_bottom" @click="reset()"><svg-icon icon-class="reset-svg" />重置</el-button>
    </template>
    <PageCard title="巡检点位">
      <template #actions>
        <el-button icon="el-icon-download" class="ed-button ed_white_bottom ed-button36" size="small"  @click="downLoadPoint" v-has="'patrol:point:download'">下载点位码</el-button>
        <el-button icon="el-icon-delete" class="ed-button ed_del_top ed-button36" size="small" @click="delSelection" v-has="'patrol:point:delete'" >删除</el-button>
        <el-button icon="el-icon-plus" class="ed-button ed_black-bottom ed-button36" size="small" @click="showPoint" v-has="'patrol:point:add'">生成点位码</el-button>
      </template>
      <ApiTable :api="tableApi" ref="table" :params="params" @selectionData="selectionData">
        <el-table-column type="selection" width="55" label="序号" align="center"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="villageName" label="项目名称"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="locationName" label="点位名称"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="locationType" label="点位类型">
          <template slot-scope="scope">
            <span v-if="scope.row.locationType == 1">设备点</span>
            <span v-else-if="scope.row.locationType == 2">位置点</span>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="url" label="点位码">
          <template slot-scope="scope">
            <QrCode style="height: 64px; width: 64px" @click.native="showerweiCode(scope.row)">
              {{ scope.row.url }}
            </QrCode>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="deployTime" label="部署时间" :formatter="formatDate"></el-table-column>
      </ApiTable>
    </PageCard>
    <!-- <ed-confirm-delete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeletePoint()" :isShow=""></ed-confirm-delete> -->
    <ed-confirm-delete  ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue()"></ed-confirm-delete>
    <el-dialog title="查看点位码" :visible.sync="dialogVisible" width="20%" :close-on-click-modal="false">
      <div class="erweicodeCenter">
        <div>
          <QrCode style="height: 135px; width: 141px">
            {{erweiCode.url}}</QrCode>
        </div>
        <div class="pointCode">
          <span>{{ erweiCode.locationType == 1 ? "设备点" : "位置点" }}:</span>
          <span>{{ erweiCode.id }}</span>
        </div>
      </div>
      <!-- <span slot="footer" class="dialog-footer downLoadCode">
                <el-button class="ed-button ed_black-bottom"  @click="dialogVisible = false"  >打印</el-button>
                <el-button class="ed-button ed_black-bottom" @click="dialogVisible = false"  >下载</el-button>
            </span> -->
    </el-dialog>

    <!-- 生成点位吗弹框 -->
    <el-dialog title="生成点位码" :visible.sync="showPointVisible" width="30%" :close-on-click-modal="false">
      <div>
        <div class="pointinfo">
          <span>注：位置点位码数量和设备点位码数量之和一次最多50个</span>
        </div>
        <el-form ref="pointformref" :model="pointform" label-width="230px" :rules="rules" >
          <el-form-item label="项目名称" prop="villageId" :rules="$validate.validates({ required: true, msg: '请选择项目名称'})">
            <EdSelect v-model="pointform.villageId" :selectParams="projectNameParams" style="width: 80%" @emit-select-value="projecPointChange"></EdSelect>
          </el-form-item>
          <el-form-item label="请输入位置点位码数量" prop="locationNum">
            <el-input v-model.number="pointform.locationNum" style="width: 80%" oninput="this.value=this.value.replace(/[^0-9]/g,'')"></el-input>
          </el-form-item>
          <el-form-item label="请输入设备点位码数量" prop="equipmentNum">
            <el-input v-model.number="pointform.equipmentNum" style="width: 80%" oninput="this.value=this.value.replace(/[^0-9]/g,'')"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer downLoadCode">
        <el-button class="ed-table-bottom ed_black_border" @click="showPointReset">取消</el-button>
        <el-button class="ed-button ed_black-bottom" @click="packageDownload" :disabled="isDownLoad">打包下载</el-button>
      </span>
    </el-dialog>

    <el-dialog title="生成点位码" :visible.sync="packageDownloadVisible" width="20%" :close-on-click-modal="false">
      <div class="erweicodeCenter">
        <div>
          <el-result icon="success" style="color: #67c23a"></el-result>
          <h4>点位码已下载</h4>
          <div>未绑定的二维码有效期30天，请及时进行点位部署</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer erweicodeCenter">
        <el-button class="ed-button ed_black-bottom" @click="packageDownloadVisible = false">确定</el-button>
      </span>
    </el-dialog>
  </Page>
</template>

<script>
import {pointList,pointDelete,downLoadCode,serveCode,projectList,checkIfPatrol,isHaveWorkDelete} from "./api.js";
import QrCode from "src/components/QrCode.vue";
import Page from "../../components/Page.vue";
import PageCard from "src/views/components/PageCard.vue";
import ApiTable from "src/components/ApiTable.vue";
import EdSelect from "src/components/EdSelect.vue";
import EdDialog from "src/components/EdDialog.vue";
import { defineComponent } from "vue";
import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
export default defineComponent({
  name: "project",
  components: {Page,PageCard,ApiTable,EdSelect,EdDialog,EdConfirmDelete,QrCode,},
  data() {
    const validatorLocationNum = (rule, value, callback) => {
      if (value + this.pointform.equipmentNum > 50) {
        return callback(
          new Error("位置点位码数量和设备点位码数量之和一次最多50个")
        );
      } else {
        callback();
      }
    };
    const validatorEquipmentNum = (rule, value, callback) => {
      if (this.pointform.locationNum + value > 50) {
        return callback(
          new Error("位置点位码数量和设备点位码数量之和一次最多50个")
        );
      } else {
        callback();
      }
    };
    return {
      pointform: {
        locationNum: 0,
        equipmentNum: 0,
        villageId: "",
        villageName: "",
      },
      rules: {
        locationNum: [{ validator: validatorLocationNum, trigger: "blur" }],
        equipmentNum: [{ validator: validatorEquipmentNum, trigger: "blur" }],
      },
      params: {
        projectName: "",
        locationType: "",
        locationName: "",
        villageId: "",
        villageName: "",
        url: "",
        id: "",
      },
      confirmRow: "",
      showCode: false,
      pickerParams: {
        placeholder: "请选择所属公司",
      },
      projectNameParams: {
        placeholder: "请选择项目名称",
        options: [],
      },
      locationTypeParams: {
        placeholder: "点位类型",
        options: [
          { label: "设备点", value: 1 },
          { label: "位置点", value: 2 },
        ],
        props: { label: "label", value: "value" },
      },
      centerDialogVisible: false,
      multipleSelection: [],
      downloadcod: [],
      ids: [],
      dialogVisible: false,
      erweiCode: {
        url: "",
        id: "",
        locationType: "",
        locationName: "",
      },
      packageDownloadVisible: false,
      showPointVisible: false,
      isHaveWork: "",
    };
  },
  computed: {
    isDownLoad() {
      let sum = this.pointform.locationNum + this.pointform.equipmentNum;
      if (sum == 0 || sum > 50) {
        return true;
      } else {
        return false;
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.load(1);
      this.initDic();
    });
  },
  methods: {
    tableApi: pointList,
    initDic() {
      projectList({pageSize: 999999}).then((response) => {
        if (response.success) {
          console.log(response);
          this.projectNameParams.options = response.data.records.map((x) => {
            return { label: x.villageName, value: x.villageId };
          });
        }
      });
    },
    search() {
      this.$refs.table.load(1);
    },
    reset() {
      (this.params = {
        projectName: "",
        locationType: "",
        locationName: "",
        url: "",
      }),
        this.$nextTick(() => {
          this.$refs.table.load(1, 10);
        });
    },
    closeDialog() {
      this.showCode = false;
    },
    saveDialog() {
      this.showCode = false;
    },
    add() {
      this.$router.push({
        path: "/patrol/plan/planAdd",
      });
    },
    del() {
      let message = ""
      if (this.isHaveWork == 1) {
        message="所选点位在巡检任务/计划中，确定删除？"
      } else {
        message="是否执行此操作？"
      }
       this.$refs.confirmDeleteRef.open(
          "操作确认",
          message,
          "warning"
      );
    },
    confirmDeleteTrue() {
      if (this.isHaveWork == 1) {
        isHaveWorkDelete(this.ids).then((response) => {
          if (response.success) {
            this.$message.success({
              message: "点位已删除成功！",
              duration: 2000,
              center: true,
            });
            this.$refs.table.load();
          }
        });
      } else {
        pointDelete(this.ids).then((response) => {
          if (response.success) {
            this.$message.success({
              message: "点位已删除成功！",
              duration: 2000,
              center: true,
            });
            this.$refs.table.load();
          }
        });
      }
    },
    selectionData(value) {
      this.multipleSelection = value;
    },
    delSelection() {
      if (this.multipleSelection.length > 0) {
        // 调多选的删除的接口,从数组对象里面取得数组ID
        let ids = this.multipleSelection.map((x) => {
          return { id: x.id };
        });
        //    this.del()
        this.ids = ids;
        //    调查询点位是否有任务的接口
        checkIfPatrol(this.ids).then((response) => {
          if (response.success) {
            this.isHaveWork = response.data.isHaveWork;
            // console.log("isHaveWork", isHaveWork);
            this.del();
          }
        });
      } else {
        this.$message.warning({
          message: "请选择要删除的数据",
          center: true,
        });
      }
    },
    downLoadPoint() {
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((v, i) => {
          this.downloadcod.push({url: v.url,id: v.id,locationType: v.locationType,locationName: v.locationName,});
        });
        // console.log("-------", this.downloadcod);
        serveCode(this.downloadcod).then((response) => {
          if (response.success) {
            this.$message.success({
              message: '下载点位码成功！',
              duration: 2000,
              center:true
            });
          } else {this.$message.error({
            message:'下载点位码失败',
            cneter:true,
          })}
        });
      } else {
        this.$message.warning({
          message: "请选择要下载的数据",
          center: true,
        });
      }
    },
    showerweiCode(row) {
      console.log(123);
      // 直接在列表里面返回给我，不要给我接口
      this.dialogVisible = true;
      this.erweiCode = row;
    },
    showPoint() {
      this.showPointVisible = true;
      this.$nextTick(() => {
        this.$refs["pointformref"].resetFields();
      });
    },
    packageDownload() {
      this.projectNameParams.options.forEach((v, i) => {
        if (this.pointform.villageId == v.value) {
          this.pointform.villageName = v.label;
        }
      });
      this.$refs["pointformref"].validate((valid) => {
        // alert(valid)
        if (valid) {
          this.showPointVisible = false;
          downLoadCode(this.pointform).then((res) => {
            if (res.success) {
              this.packageDownloadVisible = true;
              this.showPointReset();
            }
          });
        }
      });
    },
    projectChange(row) {
      let option = this.projectNameParams.options.find((x) => x.value == row);
      this.params.villageName = option.label;
    },
    projecPointChange(row) {
      let option = this.projectNameParams.options.find((x) => x.value == row);
      this.pointform.villageName = option.label;
    },
    showPointReset() {
      this.showPointVisible = false;
      this.$refs["pointformref"].resetFields();
    },
    formatDate(row, column) {
      // 获取单元格数据
      let date = row[column.property];
      if (date) {
        return this.transformDate(date);
      } else {
        return "";
      }
    },
    //标准时间格式转yyyy-MM-dd HH:mm:ss
    transformDate(date) {
      if (date) {
        let dt = new Date(date);
        return (
          dt.getFullYear() +
          "-" +
          (dt.getMonth() + 1 < 10
            ? "0" + (dt.getMonth() + 1)
            : dt.getMonth() + 1) +
          "-" +
          (dt.getDate() < 10 ? "0" + dt.getDate() : dt.getDate()) +
          " " +
          (dt.getHours() < 10 ? "0" + dt.getHours() : dt.getHours()) +
          ":" +
          (dt.getMinutes() < 10 ? "0" + dt.getMinutes() : dt.getMinutes())
        );
        // (dt.getSeconds() < 10 ? ('0' + dt.getSeconds()) : dt.getSeconds())
      } else {
        return "";
      }
    },
  },
});
</script>

<style lang="scss" scoped>
.erweicodeCenter {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .pointCode {
    margin-top: 1px;
    // justify-content:center;
    // align-items:center;
    // text-align: center;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: center;
  }
}
.downLoadCode {
  display: flex;
  justify-content:flex-end;
}
.erweicodeCenter h4 {
  text-align: center;
  margin-bottom: 15px;
}
.pointinfo {
  text-align: center;
  margin-bottom: 15px;
}
.qr-code {
  width: 300px;
  height: 300px;
}
</style>